// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");
const { filesURL } = require("../../../config");

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			cover: o.cover ? `${filesURL}/images/cover/${o.cover}` : null,
			country:
				o.country === 0 ? "国内" :
					o.country === 1 ? "日本" :
						o.country === 2 ? "欧美" : "其他",
			premiere: moment(o.premiere).format("YYYY年MM月DD日"),
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss"),
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE is_delete = 0`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("获取失败，无漫画信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 添加番剧
exports.Add = async (req, res, table) => {
	const { number, comicname, c_name, country, intro, premiere } = req.body;
	const info = { number, comicname, c_name, country, intro, premiere, creator: req.user.id };
	try {
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("新增失败");
		return res.success("新增成功");
	} catch (err) {
		return res.error(err);
	}
};

// 修改番剧
exports.Update = async (req, res, table) => {
	const { comicname, c_name, country, intro, premiere, id } = req.body;
	const info = [comicname, c_name, country, intro, premiere, id];
	try {
		const sqlStr = `UPDATE ${table} SET comicname=?,c_name=?,country=?,intro=?,premiere=? WHERE id=?`;
		const [results] = await mysql.query(sqlStr, info);
		if (results.affectedRows !== 1) return res.error("修改失败");
		return res.success("修改成功");
	} catch (err) {
		return res.error(err);
	}
};

exports.Search = async (req, res, table) => {
	const info = req.params.value;

	try {
		const sqlStr = `SELECT * From ${table} WHERE (comicname LIKE ? OR c_name LIKE ? OR intro LIKE ? OR country LIKE ? OR premiere LIKE ?) AND is_delete = 0`;
		const SeletePattern = `%${info}%`;
		const values = Array(5).fill(SeletePattern);
		const [results] = await mysql.query(sqlStr, values);
		if (results.length === 0) return res.error("该漫画不存在！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};